package org.looop.studio.bean.scope.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.looop.studio.bean.domain.BeanDefinition;
import org.looop.studio.bean.factory.BeanFactory;
import org.looop.studio.bean.scope.BeanScope;

public class SingletonScope implements BeanScope {
	private Map<String, Object> beanPool = new HashMap<String, Object>();
	@Override
	public Object getBean(BeanFactory factory, BeanDefinition beanDefinition)
			throws InstantiationException, IllegalAccessException,
			ClassNotFoundException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {
		String id = beanDefinition.getId();
		if (beanPool.get(id) == null) {
			synchronized (beanPool) {
				if (beanPool.get(id) == null) {
					Object bean = factory.createBean(beanDefinition);
					beanPool.put(id, bean);
					return bean;
				} else {
					return beanPool.get(id);
				}
			}
		}
		return beanPool.get(id);
	}

}
